<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData" :showToggleAdvanced="true" :defaultExpandAdvanced="false">
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<!-- ===== 核心搜索条件（常用） ===== -->
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="BillId_FormItem" prop="BillId">
							<template #label>
								<WtmLabelTooltip label="采购申请单" tooltip="关联的采购申请单主表" />
							</template>
							<el-select v-model="searchData.BillId" :data="stateData.AllSysPurchaseRequestBills" clearable>
								<el-option v-for="item in stateData.AllSysPurchaseRequestBills" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
							></el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="MaterialId_FormItem" prop="MaterialId">
							<template #label>
								<WtmLabelTooltip label="物料" tooltip="采购的物料" />
							</template>
							<el-select v-model="searchData.MaterialId" :data="stateData.AllSysMaterials" clearable>
								<el-option v-for="item in stateData.AllSysMaterials" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
							></el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="PurchaseProgress_FormItem" prop="PurchaseProgress">
							<template #label>
								<WtmLabelTooltip label="采购进度" tooltip="该明细行的采购进度状态" />
							</template>
							<el-select v-model="searchData.PurchaseProgress" clearable>
								<el-option key="采购审批中" value="采购审批中" label="采购审批中"></el-option>
								<el-option key="采购需求池" value="采购需求池" label="采购需求池"></el-option>
								<el-option key="采购中" value="采购中" label="采购中"></el-option>
								<el-option key="运输中" value="运输中" label="运输中"></el-option>
								<el-option key="已完成" value="已完成" label="已完成"></el-option>
								<el-option key="已取消" value="已取消" label="已取消"></el-option
							></el-select>
						</el-form-item>
					</el-col>

					<!-- ===== 高级搜索条件（可展开） ===== -->
					<template v-if="showAdvanced">
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="MaterialSkuId_FormItem" prop="MaterialSkuId">
								<template #label>
									<WtmLabelTooltip label="物料规格" tooltip="采购的物料规格" />
								</template>
								<el-select v-model="searchData.MaterialSkuId" :data="stateData.AllSysMaterialSkus" clearable>
									<el-option v-for="item in stateData.AllSysMaterialSkus" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="IsBackupMaterial_FormItem" prop="IsBackupMaterial">
								<template #label>
									<WtmLabelTooltip label="是否备用物资" tooltip="备用物资不计入物料呆滞考核" />
								</template>
								<el-select v-model="searchData.IsBackupMaterial" clearable>
									<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
									<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="RequiredArrivalDate_FormItem" prop="RequiredArrivalDate">
								<template #label>
									<WtmLabelTooltip label="要求到货日期" tooltip="该物料期望的到货日期" />
								</template>
								<el-date-picker v-model="searchData.RequiredArrivalDate" clearable></el-date-picker>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysPurchaseRequestBillEntry/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysPurchaseRequestBillEntry/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysPurchaseRequestBillEntry/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysPurchaseRequestBillEntry/SysPurchaseRequestBillEntryExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>

		<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
			<template #operation>
				<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" align="center" class-name="operation-column">
					<template v-slot="scope">
						<div class="operation-container">
							<WtmButton
								v-auth="'/api/SysPurchaseRequestBillEntry/Edit'"
								:is-text="true"
								icon="fa fa-pencil-square"
								type="warning"
								:button-text="$t('message._system.common.vm.edit')"
								@click="OnEditRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysPurchaseRequestBillEntry/{id}'"
								:is-text="true"
								icon="fa fa-info-circle"
								type="info"
								:button-text="$t('message._system.common.vm.detail')"
								@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysPurchaseRequestBillEntry/BatchDelete'"
								icon="fa fa-trash"
								type="danger"
								:button-text="$t('message._system.common.vm.delete')"
								:confirm="$t('message._system.common.vm.deletetip')"
								:is-text="true"
								@click="onDelete(scope.row)"
							/>
						</div>
					</template>
				</el-table-column>
			</template>
		</WtmTable>
	</div>
</template>

<script setup lang="ts" name="采购申请明细copy;true;HengTong.Areas.SupplyChain.Controllers;SysPurchaseRequestBillEntry">
import ElMessage from 'element-plus/es/components/message/index';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed } from 'vue';
import { SysPurchaseRequestBillEntryApi as api } from '/@/views/supplychain/syspurchaserequestbillentry/api';
import { ISysPurchaseRequestBillEntryView, ISysPurchaseRequestBillEntryQuery } from '/@/views/supplychain/syspurchaserequestbillentry/api/interface';
import other from '/@/utils/other';
import { IViewModel, ISysSelectType } from '/@/types/common';

const ci = getCurrentInstance() as any;
const loading = ref(false);
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysPurchaseRequestBillEntryQuery;
		/** 主表ID */
		entityId?: string | null;
		/** 采购申请单ID（从主表传入） */
		billId?: string | null;
		/** 需求日期（从主表传入，用于同步到要求到货日期） */
		needDate?: Date | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		entityId: null,
		billId: null,
		needDate: null,
	}
);

const stateData = reactive({
	AllSysPurchaseRequestBills: [] as ISysSelectType[],
	AllSysMaterials: [] as ISysSelectType[],
	AllSysMaterialSkus: [] as ISysSelectType[],
});

const searchData = ref<ISysPurchaseRequestBillEntryQuery>({
	BillId: null,
	MaterialId: null,
	MaterialSkuId: null,
	IsBackupMaterial: null,
	RequiredArrivalDate: null,
	PurchaseProgress: null,
});

// 定义变量内容
const tableRef = ref();
const tableData = ref({
	// 列表数据（必传）s
	data: [],
	// 表头内容（必传，注意格式）
	header: [
		{ title: '采购申请单', key: 'BillName', type: 'text', isCheck: true },
		{ title: '物料', key: 'MaterialName', type: 'text', isCheck: true },
		{ title: '物料规格', key: 'MaterialSkuName', type: 'text', isCheck: true },
		{ title: '是否备用物资', key: 'IsBackupMaterial', type: 'switch', isCheck: true },
		{ title: '申请数量', key: 'RequestQuantity', type: 'text', isCheck: true },
		{ title: '单位价格', key: 'UnitPrice', type: 'text', isCheck: true },
		{ title: '总金额', key: 'TotalAmount', type: 'text', isCheck: true },
		{ title: '预算金额', key: 'BudgetAmount', type: 'text', isCheck: true },
		{ title: '技术要求', key: 'TechnicalRequirement', type: 'text', isCheck: true },
		{
			title: '要求到货日期',
			key: 'RequiredArrivalDate',
			type: 'date',
			isCheck: true,
			formatter: (row: any, value: any) => {
				if (!value) return '';
				const date = new Date(value);
				return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '-');
			},
		},
		{ title: '采购进度', key: 'PurchaseProgress', type: 'text', isCheck: true },
		{ title: '附件', key: '', type: 'text', isCheck: true },
	],
	// 配置项（必传）
	config: {
		total: 0, // 列表总数
		loading: true, // loading 加载
		isSerialNo: true, // 是否显示表格序号
		isSelection: true, // 是否显示表格多选
		isOperate: props.isDisabled, // 是否显示表格操作栏
	},
});
// 初始化表格数据
const getTableData = async () => {
	// 优先使用 billId，其次使用 entityId
	if (props.billId) {
		searchData.value.BillId = props.billId as string;
	} else if (props.entityId) {
		searchData.value.BillId = props.entityId as string;
	}
	try {
		await tableRef.value.doSearch(api().search, searchData.value);
	} catch (error) {
		other.setFormError(ci, error);
	}
};
const OnCreateClick = () => {
	// 如果有billId，将其作为wtmdata传递给创建对话框
	const wtmdata: any = props.billId ? { BillId: props.billId } : {};
	// 如果有需求日期，也传递给创建对话框，用于同步到要求到货日期
	if (props.needDate) {
		// 确保日期对象正确传递（处理可能的字符串或Date对象）
		const needDate = props.needDate instanceof Date ? new Date(props.needDate.getTime()) : new Date(props.needDate);
		// 验证日期是否有效
		if (!isNaN(needDate.getTime())) {
			wtmdata.NeedDate = needDate;
		}
	}
	other.openDialog(ci.proxy.$t('message._system.common.vm.add'), CreateDialog, wtmdata, getTableData);
};

const OnEditRowClick = (row: ISysPurchaseRequestBillEntryView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.edit'), EditDialog, row, getTableData);
};

const OnDetailsRowClick = (row: ISysPurchaseRequestBillEntryView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.detail'), DetailsDialog, row, getTableData);
};

// 删除
const onDelete = (row: ISysPurchaseRequestBillEntryView) => {
	const ids = [row.ID] as (string | number)[];
	api()
		.delete(ids)
		.then(() => {
			getTableData();
		});
};

//批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysPurchaseRequestBillEntryView) => x.ID) as (string | number)[];
	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			// 先清除选择状态
			tableRef.value?.clearSelection();
			// 再重新获取数据
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy.$t('message._system.common.vm.error'));
		}
	} else {
		ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
	}
};
// 添加计算属性判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

const OnImportClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.import'), ImportDialog, null, getTableData);
};

const onExport = () => {
	const selected = tableRef.value.getSelectedRows();
	if (selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 页面加载时
onMounted(() => {
	loading.value = true;
	const promises: Promise<any>[] = [
		other
			.getSelectList('/api/SysPurchaseRequestBillEntry/GetSysPurchaseRequestBills', [], false)
			.then((x) => (stateData.AllSysPurchaseRequestBills = x)),
		// other.getSelectList('/api/SysPurchaseRequestBillEntry/GetSysMaterials', [], false).then((x) => (stateData.AllSysMaterials = x)),
		// other.getSelectList('/api/SysPurchaseRequestBillEntry/GetSysMaterialSkus', [], false).then((x) => (stateData.AllSysMaterialSkus = x)),

		getTableData(),
	];
	Promise.allSettled(promises).finally(() => {
		loading.value = false;
	});
});
</script>
